import { Gateway } from "@/entity/gateway.entity";
import { Repository } from "typeorm";
import * as state from '../state'

// 更新网关表
export async function updateGw(gw: state.GwObject, gatewayRepo: Repository<Gateway>) {
    // 创建 Gateway 实例
    let gateway = new Gateway();
    gateway = {
        ...gw,
        outdoor: gw?.outdoor || false,
        version_fs: gw?.version_fs || '',
        version_bin: gw?.version_bin || '',
        time: gw?.time || new Date(),
        deleted: gw?.deleted || false,
        last_report_time: gw?.last_report_time || new Date(),
        last_report_wb_cnt: gw?.last_report_wb_cnt || '0',
        reg_time: null,
        topic: '',
        scene: '',
        photo: '',
        class: null
    }
    // console.log('last_report_wb_cnt', gateway.last_report_wb_cnt)
    // 添加字段至 gateway 表
    // 1. 先判断 mac 是否为空
    if (!gateway?.mac) return; // 为空时直接返回
    // 2. 判断是否存在对应的 gateway
    const existingGateway = await gatewayRepo.findOne({ where: { mac: gateway.mac } });
    // 3. 对于存在和不存在新增或更新
    if (!existingGateway) {
        // Insert if the gateway does not exist
        // 入网时间
        gateway.reg_time = new Date()
        await gatewayRepo.insert(gateway);
    } else {
        // Update if the gateway already exists
        const updateData = {
            version_fs: gateway.version_fs,
            version_bin: gateway.version_bin,
            time: gateway.time,
            deleted: gateway.deleted,
            last_report_time: gateway.last_report_time,
            last_report_wb_cnt: gw?.last_report_wb_cnt || '0',
            // 明确不包含 class 字段
        };
        // time: gw.time
        try {
            await gatewayRepo.update(
                { mac: gateway.mac }, updateData);

        } catch (err) {
            console.log(err)
        }
    }
}

// 获取所有网关
export async function getAllGateways(gatewayRepo: Repository<Gateway>) {
    const query = gatewayRepo.createQueryBuilder('gateway')
        .leftJoinAndSelect('gateway.class', 'class') // 关联 class
        .leftJoinAndSelect('class.school', 'school')
    // 按时间降序排列
    query.orderBy('gateway.time', 'DESC');
    // 查询总数 count
    const total = await query.getCount();
    // return await this.gatewayRepo.find({ relations: ['class'] }); // 加载关联的班级
    // 返回数据

    return await query.getMany()
}